#!usr/bin/env python3
#-*- coding:utf-8 -*-
#PyQt5系列教程（7）：界面搭建
#https://zhuanlan.zhihu.com/p/28774180

import sys,time
from PyQt5.QtWidgets import QApplication,QMainWindow,QAction,qApp,QMenu
from PyQt5.QtGui import QIcon

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
    
    def initUI(self):
        statusBar = self.statusBar()
        statusBar.showMessage("装备就绪")

        self.setWindowTitle("快乐软件")
        self.setGeometry(350,200,500,400)

        self.menu = self.menuBar() #横向加菜单
        self.fileMenu = self.menu.addMenu("文件(&F)")
        self.editMenu = self.menu.addMenu("编辑(&E)")

        
        self.fileMenu.addAction( self.createAction("打开(&O)",qApp.quit,"assets/ico/import.png","ctrl+O","打开文件") )
        
        #添加子菜单
        saveAsMenu = QMenu("保存方式",self)
        saveAsMenu.addAction( self.createAction("另存为(&SA)",qApp.quit,"assets/ico/export.png","ctrl+shift+s","另存为->") )
        saveAsMenu.setIcon(QIcon("assets/ico/logo.png"))
        self.fileMenu.addMenu(saveAsMenu)

        qAct = self.createAction("退出(&E)",qApp.quit,"assets/ico/exit.png","ctrl+Q","点击退出")
        self.fileMenu.addAction( qAct )

        #上下文菜单，右键菜单 看 contextMenuEvent 函数

        #工具栏
        toolBar = self.addToolBar("工具栏")
        toolBar.addAction(qAct)
        
    def createAction(self,text:str,fn,icoUrl:str="",sc:str="",tips:str=""):
        action = QAction(QIcon(icoUrl),text,self)
        action.setShortcut(sc)
        action.setStatusTip(tips)
        action.triggered.connect(fn)
        return action 

    #上下文菜单，右键菜单;重写父类函数，右键触发
    def contextMenuEvent(self,event):
        menu = QMenu(self)
        menu.addAction("新建")
        menu.addAction("保存")
        qAct = menu.addAction("退出")
        act = menu.exec(self.mapToGlobal(event.pos())) #执行exec才能显示菜单
        if qAct==act:
            qApp.quit()

if __name__=="__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec())
